package com.mall.mymall.enums;

import lombok.Getter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public enum Roles implements GrantedAuthority {
    // 超级管理员
    SUPER_ADMIN_USER(5, "SUPER_ADMIN_USER"),
    // 区域管理员
    AREA_ADMIN_USER(4, "AREA_ADMIN_USER"),
    // 商店管理员
    STORES_ADMIN_USER(3, "STORES_ADMIN_USER"),
    // VIP用户
    VIP_USER(2, "VIP_USER"),
    // 用户
    USER(1, "USER");

    @Getter
    private final Integer roleCode;
    private final String roleName;

    Roles(Integer roleCode, String roleName) {
        this.roleCode = roleCode;
        this.roleName = roleName;
    }

    public static Roles getRoleByCode(Integer roleCode) {
        for (Roles role : Roles.values()) {
            if (role.roleCode.equals(roleCode)) {
                return role;
            }
        }
        throw new RuntimeException("不支持的用户类型");
    }

    public static List<GrantedAuthority> IssueRole(Integer roleCode) {
        return Arrays.stream(Roles.values())
                .filter(role -> role.roleCode <= roleCode)
                .map(role -> toGrantedAuthority(role.roleName))
                .collect(Collectors.toList());
    }

    /**
     * 获取权限级别
     *
     * @return 返回结果
     */
    @Override
    public String getAuthority() {
        return this.roleName;
    }

    /**
     * 根据code得到权限级别
     *
     * @param roleCode code值
     * @return 返回的数据
     */
    public static String getAuthority(Integer roleCode) {
        return getRoleByCode(roleCode).roleName;
    }

    public static GrantedAuthority toGrantedAuthority(String roleName) {
        return new SimpleGrantedAuthority(roleName);
    }
}
